<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/1/21 10:19
 * Remark:
 */

namespace App\Http\Controllers\Company;

use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Consts\Role\RoleConsts;
use App\Consts\TableConsts\TableConsts;
use App\Func\ApprovalFunc;
use App\Func\CurlFunc;
use App\Func\DictionaryFunc;
use App\Func\DingTalkMsgFunc;
use App\Func\EncryptionFunc;
use App\Func\ExcelFunc;
use App\Func\FileFunc;
use App\Func\HuaWei\ObsFunc;
use App\Func\MeLawCaseAllocation;
use App\Func\MeLawCaseFunc;
use App\Func\ResponseFunc;
use App\Func\RoleFunc;
use App\Func\SMSFunc;
use App\Func\TokenFuc;
use App\Http\Controllers\Controller;
use App\Http\Controllers\MeSms\MeSMSController;
use App\Http\Controllers\YsApproval\YsApprovalController;
use App\Http\Requests\Company\AddCompanyPost;
use App\Http\Requests\Company\ListCompanyGet;
use App\Models\Auth\RoleModel;
use App\Models\Log\LoginLog;
use App\Models\MeClient\MeClientModel;
use App\Models\MeLawCase\MeLawCase;
use App\Models\MeLawCase\MeLawCaseLawLetterModel;
use App\Models\MeLawCase\MeLawCasePhoneModel;
use App\Models\SMS\SMSLogModel;
use App\Models\SMS\SMSUpstreamModel;
use App\Models\Staff\StaffRoleModel;
use App\Service\Company\CompanyService;
use App\Service\MapService\TableMapService;
use App\Service\MeCaseSerice\ImportLawCase;
use App\ServiceChecker\OperateChecker\DeleteOperateChecker;
use App\Tools\DingTalk\DingTalkApprovalProcess;
use App\Tools\DingTalk\DingTalkUploadFacade;
use App\Tools\File\ExcelFile;
use App\Tools\Oss\OssTools;
use App\Tools\QxwgSMS\QxwgController;
use App\Tools\ShortLink\ShortLinkFunc;
use App\Tools\Sms\DbaicaiSms;
use App\Tools\USails\USailsBasic;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Env;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use OapiSnsGetuserinfoBycodeRequest;

class CompanyController extends Controller
{
    private CompanyService $_companyService;

    public function __construct()
    {
        $this->_companyService = new CompanyService();
    }


    public function test(){
//        $fileUrl = "https://telephone-recording-1305187735.cos.ap-chengdu.myqcloud.com/records/8/2023-08-29/18001/a894429e-d302-434f-bf2f-834ef064b979.wav?sign=q-sign-algorithm%3Dsha1%26q-ak%3DAKIDEH5cuwiDRQ7YicGchW4LL4XjeJiqhHbd%26q-sign-time%3D1693896137%3B1693903337%26q-key-time%3D1693896137%3B1693903337%26q-header-list%3Dhost%26q-url-param-list%3D%26q-signature%3Ddc8f2e5a47ab1a95497438abc51746ca3831ee93";
//        $contents = file_get_contents($fileUrl);
//        $tempFile = tempnam(sys_get_temp_dir(), 'file');
//        file_put_contents($tempFile, $contents);
//
//        $dir = date("Ymd");
//        $filePath =  $dir;
//        $res = Storage::disk('obs')->putFile($filePath, $tempFile);
////        // 存储fileModel
//        $res ="";
//        unlink(Storage::path("obs/20230905/0KHtdzaRJEw530l3QaF78gs25uU5hxf2CmSvZ4Pp.wav"));
//        dd(1);
//        $obsFunc = new ObsFunc();
//        return $obsFunc->downloadFileByUrl("20230906/1693983028.wav");
//        die();
//        $obsFunc->uploadVideoByPath(Storage::path("obs/".$res));
//        dd(1);
////        $encryptionFileUrl = "file".DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.md5($originalName.time()).".".$ext;
////        $res = Storage::disk('local')->put($encryptionFileUrl,file_get_contents($path));
//        $ObFunc = new ObsFunc();
//        $ObFunc->uploadVideo();
//        die();
//
//        $fileF = new FileFunc();
////        $fileF->zipDir(
////            __DIR__
////        );
//        $fileF->zipFiles(
//            [
//                __DIR__.DIRECTORY_SEPARATOR.'a.html'
//            ]
//        );
//        dd(1111);
        $me = new MeLawCaseLawLetterModel();
        $info = $me->select([
            'law_case_law_letter.pdf_path_hash'
        ])->leftJoin(TableConsts::ME_LAW_CASE." as law",'law.law_case_id','law_case_law_letter.law_case_id')
        ->where('law.client_id',16)
        ->where('law.law_case_batch_number',6)
        ->get();
        $newFmt = [];
        foreach($info->toArray() as $key=>$value){
            $newFmt[] = "https://me.cyhzsoft.com/api/index.php/l/doletter/".$value['pdf_path_hash'];
        }
        dd(implode("\r\n",$newFmt));
        $mc = new MeSMSController();
        $mc->getCallBackByDabaicai();
        die();
        return json_encode(['ok'=>1]);
//        (new USailsBasic())->registerCallBack();
        dd(1);
//        $lc = new ImportLawCase();
//        $r = $lc->urlImportEncode('{"data":{"used":"test","time_stamp":1000000000}}');
        dump($r);
        $lc->urlImportDecode($r);
        dd();

//        $ef = new ExcelFunc();
//        $res =  $ef->readFirstRow(604);
//        $qxbc = new QxwgController();
//        $qxbc->p2pSendSms([
//            '17748119841' => "【青羊蓉城金融调解】张大里，申请人给予您调解方案，为避免超时失效，请您及时回复。同意回Y，退订T"
//        ]);
//        dd($res);
//        return $encrypted;
//        通过短信日志发送短信
//        $smsLog = new SMSLogModel();
//        $res = $smsLog->get()->toArray();
//        $client = DbaicaiSms::getInstance();
//        $client->changeRequestType('POST');
//        $messageList = [];
//        foreach($res as $v){
//            // 获取主叫号码
//            $messageList[] = [
//                'phone' => $v['phone'],
//                'content' => $v['sms_info']
//            ];
//        }
//
//        $data = $client->sendMsg($messageList);
//        $res = $client->execute('api/sendMessageOne',$data);
//        $fmtRes = json_decode($res,true);
//        dd($fmtRes);
//        dd($res->toArray());
        dd(1);
        $hash_id = '2c66455d673181939cee3ec73740f1433d0882f2f4bd4ab76abf16305e72d6d6';
        $lawCaseLawLatterModel = new MeLawCaseLawLetterModel();
        $latterInfo = $lawCaseLawLatterModel->getInfoByHash($hash_id);

        $images = Storage::disk('local')->files('lawLatter/20230620/902db81498eedd7bf1065aaf5c4a3afa');
        // 遍历图片并将图片转换成 base64 编码
        foreach ($images as $image) {
            // 获取图片内容并进行 base64 编码
            $base64Image = base64_encode(Storage::disk('local')->get($image));
            // 输出 base64 编码后的图片
            dd($base64Image);
        }
        dd(json_encode([
            'name' => "周林浩",
            'baodancode' => "50177771",
            'bankname' => "中国瞎编乱造银行",
            'endtime' => "2024-06-01",
            'money' => "10.00",
        ],256));
//        $mlcal = new MeLawCaseAllocation();
//        $roleFunc = new RoleFunc();
//        $staffIds = $roleFunc->getStaffIdsByRoleCode(RoleConsts::ROLE_TYPE_TJY);
//        $mlcal->lawCaseAllocation(cases: [
//            ["lawCaseId" => 44717, "money" => 7711],
//            ["lawCaseId" => 44716, "money" => 10789.1],
//            ["lawCaseId" => 44715, "money" => 7677],
//            ["lawCaseId" => 44714, "money" => 1237.8],
//            ["lawCaseId" => 44713, "money" => 8007],
//            ["lawCaseId" => 44712, "money" => 5225.21],
//            ["lawCaseId" => 44711, "money" => 7244.4],
//            ["lawCaseId" => 44710, "money" => 3700],
//            ["lawCaseId" => 44709, "money" => 2145],
//            ],num_workers:$staffIds);
//        dd("ok");
        dd(ShortLinkFunc::coverShortUrl("1111"));
        $client = DbaicaiSms::getInstance();
        $client->changeRequestType("POST");
        $data = $client->sendMsg([
            'phone' => '15828111021',
            'content' => "【青羊蓉城金融调解】12345，我方已受理北京恒元信业关于你通过[12456]发生的民间借贷纠纷案件的调解申请。详情回 Y，退订回 T"
        ]);
        dd($client->execute('api/sendMessageOne',$data));
        die("禁止访问");
        $ilc = new ImportLawCase();
        $url = "https://47.108.159.96:39351/setProceedMap";
        echo "准备进入循环";
        // ID自增
        $count = 0;
        $customKey = [];
        $systemKey = [];
        try {
            $ilc = new ImportLawCase();
            $clientModel = new MeClientModel();
            // 查询映射
            $url = "https://47.108.159.96:39351/setProceedMap";
            app()->gcHelper->gfGetRedis()->list("zlh_test_kz")->for_each(function ($v,$list_length) use (&$customKey,&$systemKey,&$resData,$ilc,$clientModel,$url,&$count) {
                // 取出数据转化为数组
                $vArr = json_decode($v,true);
                $fmtEx = json_decode($vArr['Extra_parameter'],true) ?? [
                        'file_id' => 9999,
                        'client_id' => 12,
                    ];
                // 遍历并且获取对应的key
                if(isset($vArr['Is_header']) && $vArr['Is_header']){
                    // 如果是header需要清空一次
                    $customKey = [];
                    $systemKey = [];
                    $clientInfo =  $clientModel->getById($fmtEx['client_id'],['client_custom_json','client_map_excel_file_column_header_to_database_table_field']);
                    $customArr = $clientInfo['client_custom_json'] ? json_decode($clientInfo['client_custom_json'],true) : [];
                    $systemArr = $clientInfo['client_map_excel_file_column_header_to_database_table_field'] ? json_decode($clientInfo['client_map_excel_file_column_header_to_database_table_field'],true)['map_excel_file_column_header_to_database_table_field'] : [];
                    $excelData = $vArr['Value'];
                    // trim字符串
                    foreach($excelData as $vKey => $vValue){
                        $excelData[$vKey] = str_replace(["\"","\n","\t","\r","年","月","日"],["","","","","-","-",""],$vValue);
                    }
                    foreach($customArr as $cKey => $cValue){
                        foreach($excelData as $excelKey => $excelValue){
                            if($excelValue == $cValue['title']){
                                $customKey[$excelKey] = $cValue['key'];
                                // 剔除数据降低数组长度
                                unset($excelData[$excelKey]);
                            }
                        }
                    }
                    foreach($systemArr as $sKey => $sValue){
                        foreach($excelData as $excelKey => $excelValue){
                            if($excelValue == $sValue['title']){
                                $systemKey[$excelKey] = $sValue['field'];
                            }
                        }
                    }
                    return false;
                }else{
                    $vData = $vArr['Value'];
                    foreach($vData as $vKey => $vValue){
                        $vData[$vKey] = str_replace(["\"","\n","\t","\r","年","月","日"],["","","","","-","-",""],$vValue);
                    }
                    // 保存需要请求的Req
                    $customReq = [];
                    $systemReq = [];
                    foreach($vData as $vDataKey => $vDataValue){
                        if(isset($customKey[$vDataKey])){
                            $customReq[$customKey[$vDataKey]] = $vDataValue;
                        }
                        if(isset($systemKey[$vDataKey])){
                            $systemReq[$systemKey[$vDataKey]] = $vDataValue;
                        }
                    }

                    $defaultReq = [
                        'client_id' => $fmtEx['client_id'] ?? 0,
                        'law_case_code' => MeLawCaseFunc::getLawCaseUnionCode($fmtEx['client_id'],$count),
                        'owner_id' => $fmtEx['owner_id'] ?? 0,
                        'law_case_custom' => json_encode($customReq,256)
                    ];
                    $sqlReq = array_merge($defaultReq,$systemReq);
                    dd($sqlReq);
                    // 实例化类
                    static $flag = true;
                    static $meModel = "";
                    static $mePhone = "";
                    static $db = "";
                    if($flag){
                        $meModel = new MeLawCase();
                        $mePhone = new MeLawCasePhoneModel();
                        $flag = false;
                    }
                    if($sqlReq['respondent_phone_ids']){
                        // 校验手机号是否存在 如果已经存在则不进行添加
                        $isExists = $mePhone->getDataByPhone($sqlReq['respondent_phone_ids']);
                        if(!$isExists){
                            // 加入号码表
                            $phoneId = $mePhone->add([
                                'phone_number' =>$sqlReq['respondent_phone_ids'],
                                'phone_status' => 1,
                                'is_law_case_main_phone' => 1,
                                'status' => 1,
                            ]);
                            $sqlReq['respondent_phone_ids'] = $phoneId;
                            $sqlReq['main_respondent_phone_id'] = $phoneId;
                        }else{
                            $sqlReq['respondent_phone_ids'] = $isExists['law_case_phone_id'];
                            $sqlReq['main_respondent_phone_id'] = $isExists['law_case_phone_id'];
                        }
                    }
                    $count++;
                    $id = $meModel->add($sqlReq);
                    echo "结束数据导入 导入数据ID为".$id."\n";
                }
            });
            // 没有队列自动休息一秒
//                sleep(1);
        }catch (\Exception $exception){
            // 存在异常
            echo $exception->getMessage();
        }
        dd(1);
        return 0;



        //
        var_dump(strtotime('2018年03月06日'));
        die();
//        return json_encode([1,2,3]);
        dd((new ImportLawCase())->urlImportEncode('/www/wwwroot/mediation/app/Tools/bin.shell/t.xlsx'));
        dd(Storage::path('file/20230213/5514d5273a5fe8cc9ed3118aa70137c3.doc'));
        app()->gcHelper->gfGetRedis()->list("zlh_test")->for_each(function ($v,$list_length) use (&$resData) {
            // 取出数据转化为数组
            $vArr = json_decode($v,true);
            dd($vArr);
            // 取出Value数据
            $fmtValue =  $vArr['Value'];
            dd($vArr);
        });
//        (new DbaicaiSms())->getSign("测试内容");
        $client = DbaicaiSms::getInstance();
        $client->changeRequestType('POST');
//        $data = $client->test([
//            'phone' => '15828111021',
//            'content' => "【四川省企业经济促进会人民调解委员会】测试"
//        ]);
        $data = $client->sendMsg([
            'phone' => '17748119841',
            'content' => "【青羊蓉城金融调解】12345，我方已受理北京恒元信业关于你通过
[12456]发生的民间借贷纠纷案件的调解申请。详情回 Y，退订回 T"
        ]);
        dd($client->execute('api/sendMessageOne',$data));
        dd();
        try {
            $a = new A();
            $a->A();
        }catch (\Exception $exception){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                $exception->getResponse()->getContent(),
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }


        die();
        return ResponseFunc::returnJson(
            'ok',
            [
                "ding_talk_approval_id" => 1
            ],
            '发起审批实例成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );
        $fm = new FulfillmentNodeModel();
        $fmnIds = array_column($fm->getFulfillmentNodeListByContractId(108,['fulfillment_node_id'])->toArray(),null,'fulfillment_node_id');
        dd($fmnIds);
//        $creditClientModel = new CreditClientModel();
//        # 获取最新的信用客户表ID 把其他的状态变更为历史
//        $creditId = $creditClientModel->getCreditClientListByClientId(2,['credit_client_id'])['credit_client_id'];
//        $creditClientModel->where('client_id',2)->where('credit_client_id','!=',$creditId)->update([
//            'status' => 2
//        ]);
        dd();
        DingTalkMsgFunc::normalRemindMessage([69,70],"测试哇","册数");
//        return CurlFunc::CurlPost();
        dd();
//        dd(1 ? 3 : 5);
//        $path = storage_path('mbfiles/client-evaluation-template.docx');
//        $savePath = storage_path('app/public/');
//        dd(CurlFunc::sendPost('http://127.0.0.1:8362/replaceTemplate',[
//            'templateDataJsonStr' => '{"clientType":"生产型"}',
//            'inputFileAddress' => $path,
//            'outputFileAddress' => $savePath
//        ]));
//        dd(date("Y-m-d h:i:s"));
//        dd(1);
//        echo json_encode([1,2,3,4]);
//        dd();
//        return DingTalkApprovalProcess::downApprovalProcessFile(63549164447,'nNtot0nxSsS6tr4We99WUw08751657250152');
//        die();
//        dd(DingTalkApprovalProcess::getContractApprovalProcessInfo("t9cDrnAPRY6Ns7qA09vILg08751657259416"));
//        $res = DingTalkApprovalProcess::getContractApprovalProcessInfo("nNtot0nxSsS6tr4We99WUw08751657250152");
//       $op =  new OldDingTalkApprovalService();
//       return $op->getDingTalkApprovalRecode("t9cDrnAPRY6Ns7qA09vILg08751657259416");
////        dd();
        $a =  new YsApprovalController();
        return $a->test();
        dd();
        dd(TokenFuc::getCurrentStaffInfo());
        Redis::set("1",1);

        die();
        $ref = new \ReflectionClass("du");
        dd($ref);
        var_dump($ref->getAttributes("See")[0]->getName());
        var_dump($ref->getAttributes("See")[0]->getArguments());
        die();
        $staffModel = new LoginLog();
        $ef = new ExcelFile();
        $head = [
            '啊实打实',
            'sta阿达色ff_id',
            'login213_ip',
            'login_123location'
        ];
        $res = $staffModel->getStaffLoginLog(46);
        return $ef->fileAllExport($head,$res->toArray(),TableConsts::CY_LOGIN_LOG_TABLE_NAME,"导出");
        die();
        $a = new DeleteOperateChecker();
        $b = new TableMapService();
        $b->returnTableMapRelationByTableName(1,TableConsts::CY_COMPANY_TABLE_NAME);
        dd();
        die();
        $fileInfo = file_get_contents(__DIR__."/1.txt");
        $res = json_decode($fileInfo,true)['data'];
        $stock_holder_list = [
            $res['stock_holder_one'],
            $res['stock_holder_two'],
            $res['stock_holder_three'],
            $res['stock_holder_four'],
            $res['stock_holder_five'],
            $res['stock_holder_six'],
            $res['stock_holder_seven'],
            $res['stock_holder_eight'],
            $res['stock_holder_nine'],
            $res['stock_holder_ten']
        ];
        $unionCompanyIds = [];
        foreach($stock_holder_list as $key => $value){
            if(!$value){
                unset($stock_holder_list[$key]);
                continue;
            }
            foreach ($value as $vv){
                $unionCompanyIds[] = ["key"=>$vv['name']];
                if($vv['stock_holder']){
                    foreach ($vv['stock_holder'] as $vvv){
                        $unionCompanyIds[] = ["key"=>$vvv['name']];
                    }
                }
            }
        }
        $uniqueFormat = array_column($unionCompanyIds,'key','key');
        foreach($stock_holder_list as &$value){
            foreach ($value as &$vv){
                $vv['id'] = md5($uniqueFormat[$vv['name']]);
                if($vv['stock_holder']){
                    foreach ($vv['stock_holder'] as &$vvv){
                        $vvv['id'] = md5($uniqueFormat[$vvv['name']]);
                    }
                }
            }
        }
        $data = [
            'stock_holder_list' => $stock_holder_list,
            'enterprise' => $res['enterprise'],
            'actual_invest_path' => $res['actual_invest_path'],
            'econ_kinds' => $res['econ_kinds'],
            'child_statics' => $res['child_statics'],
        ];
        dd($data);
//        Con
//        dd(   $filename = __DIR__ . "isv2.log");
////        dd(DingTalkCallBackFacade::deleteRegisterCallBack());
////        dd(DingTalkCallBackFacade::registerCallBack());
//        dd((app()->gcHelper->m_cDataF)()->checkerDictionaryHasNodesByParentKey("lending_status",1,"错了错了"));
//        die();
        $cs = new ContractService();
        dd($cs->getNewestContractDetailByContractId(5));
        die();
        $c = new ContractFormatTemplateService();
        $config =<<<a
        {
    "clienType":"测试替换",
    "version":"2022",
    "subVersion":"A",
    "date":"2022-05-11",
    "code":"ZHJL018",
    "typeRatingA":[0.1,0.2,0.3],
    "typeRatingB":[0.1,0.2,0.3],
    "typeRatingC":[0.1,0.2,0.3],
    "typeRatingD":[0.1,0.2,0.3],
    "departmentName":"开发部门",
    "clientName":"四川超跃汇智科技有限公司",
    "totalRating":"0",
    "clientLevel":"一级",
    "maxQuota":"1000.00",
 "clientUrl":"http://www.oa.com/#/client/15",
    "typeList":[
        {
            "typeTitle":"测试标题1",
            "lines":[
                {"title":"国有控股","type":"控股类型","ratio":"10","desc":"评价描述","rating":"10分"},
                {"title":"不是控股类型","type":"控股类型1","ratio":"20","desc":"评价描述1","rating":"5分"}
            ]
        },
        {
            "typeTitle":"测试标题2",
            "lines":[
                {"title":"国有控股","type":"控股类型","ratio":"2","desc":"评价描述123","rating":"5分"},
                {"title":"不是控股类型","type":"控股类型1","ratio":"20","desc":"评价描述1","rating":"200分"}
            ]
        }
    ]
}
a;

        $c->formatClientEvaluationTemplate($config);
        dd();
//        $code = [
//            'code' => 1234
//        ];
//        BaseAliSms::sendSMS("阿里云短信测试",
//            'SMS_154950909',
//            '17748119841',
//            json_encode($code)
//        );
//        dd(ContractFunc::getContractCodeByContractType(1,66,3));
        die();

        dd( (app()->gcHelper->m_cFile)()->setFileToDingTalk(149,"HT20220512001348111477") );
        dd();
        $up = new DingTalkUploadFacade();
        $res = $up->getUploadInfoHeaders('咕咕.docx',17753747,0,3950635511,'3zvK7gPxEPVt1YAF4piPIywiEiE');
        dump($res);
        // E:\phpstudy_pro\WWW\dms-lar-be\storage\app\file/20220222/3a51c1623be8a608b0d41cc9deecb092.docx
        OssTools::OSSUpload(
            securityToken: $res->accessToken,
            accessKeyId: $res->accessKeyId,
            accessKeySecret: $res->accessKeySecret,
            endPoint: $res->endPoint,
            bucket: $res->bucket,
            ossKey: $res->mediaId,
            filePath:file_get_contents('E:\phpstudy_pro\WWW\dms-lar-be\storage\app\file/20220222/3a51c1623be8a608b0d41cc9deecb092.docx')
        );

        dd($up->dingTalkUpload(149));
//        dd($up->dingTalkUpload("HT20220510","3zvK7gPxEPVt1YAF4piPIywiEiE","3950635511"));
//        dd();
//        DingTalkUploadFacade::test();
//        $mid = "#iAEHAqRmaWxlA6h5dW5kaXNrMATOISsHoAXNBcMGzW2cB85iejeuCM0Bdg";
//        $spaceId = "3950635511";
//        $spaceType = "org";
        $fileName = '3a51c1623be8a608b0d41cc9deecb092.docx';
        dump($up->getSpacesListByUnionId("3zvK7gPxEPVt1YAF4piPIywiEiE"));
//        dd($up->dingTalkUpload(150));
//        $upp = new DingTalkUploadFacade();
//        return $upp->getSpacesListByUnionId("3zvK7gPxEPVt1YAF4piPIywiEiE");
        die();
//        $res = $a->getDefaultClientUpdatePeriodByCreditClientId(4);
//        dd($res);
//        DingTalkApprovalProcess::getUserApprovalProcessCount('110469380821615386');
//        DingTalkApprovalProcess::getApprovalSchema();
        DingTalkApprovalProcess::sendOldApprovalProcess();
        die();
        return ApprovalFunc::getDingTalkUserIdByUserIds([
            '46',
            '47'
        ]);
        $str = "dnjTDN0gEu\/yUBFUhPoqN\/Da8tR1h9piPskuzIgb18iidVmr9HoModPpZvZc4B3E+5hBB+eHYtyc9I\/nkhXlKPM96QT2tVYlLBStRabnu7yjY\/Q250LovkQRKGo9GW+00G2jrvkw4wz52SMXMQmO3KnmJv2nuqUB+x3bLPdtEjJGI6LnRW0iuqslOk\/P9oZ\/28ClCdQvU4bnp95pfo8d2oCM8qD0Ex5Lw2HomrvO\/7cpkPXapLscef5t3jvUObV3Q02jZmuLSRIuM01cBCaedN85MumQ7KbFGZOanJaV8s0=";
        $code = "44abbb75e12436db8de94d2bfaad9846";
        die();
        $res = request()->all();
        $path = __DIR__."/1.php";
        $a = file_put_contents($path,json_encode($res));
        echo $a;
        die();
        dd();
        // 获取 Asst
        $code  =  "0169633ada4d3cfdbf42e0728fd34629";

        $bestUrl = "https://oapi.dingtalk.com/sns/getuserinfo_bycode";
        $appid = "dingoai3kwqr2ewlrx7nxi";
        $scri = "SyyXPSHCybJxALD-EIhEw83BVWdZ0m_4yiM8MBlHqEfaJrktgv1Hgowd9dg2Tvfb";
        $userGetRequest = new OapiSnsGetuserinfoBycodeRequest();
        $userGetRequest->setTmpAuthCode($code);
//        $userInfo = DingTalkApprovalProcess::getDingTalkOldClient()->executeWithAccessKey($userGetRequest,$bestUrl,$appid,$scri);
//        dd($userInfo);
        die();
        if(isset($userInfo->errcode) && $userInfo->errcode){
            throw new HttpResponseException(ResponseFunc::returnJson(
                'error',
                '',
                "钉钉客户端错误:".$userInfo->errmsg,
                ResponseStatusConsts::INTERNAL_SERVER_ERROR_500_RESPONSE_STATUS
            ));
        }
        return $userInfo->result;
        echo 123;

//        $data = request()->all();
//        $sign = EncryptionFunc::getLoginSign(
//            $data['staff_login_account'],
//            $data['staff_login_password'],
//            $data['company_id'],
//            $data['timestamp'],
//        );
//        if($sign != $data['sign']){
//            return ResponseFunc::returnJson(
//                'error',
//                null,
//                '签名错误',
//                ResponseStatusConsts::CREATED_201_RESPONSE_STATUS
//            );
//        }

        dd();
        dd(EncryptionFunc::decryptOpenssl($a['company_id'],$iv));
        dd(EncryptionFunc::decryptOpenssl($a['staff_login_password'],$iv));
        dd(openssl_decrypt(base64_decode("Mlr9Y9LWQHK5DXoRTbWQCA=="), 'AES-256-CBC', "1234567812345678", 1, "1234567812345678"));
        dd(EncryptionFunc::encode("123",Env::get('APP_KEY'),"1234567812345678"));


        die();
//        return DingTalkApprovalProcess::downApprovalProcessFile('56542130880',"6VPluIikQ6edzmAD_UsEYA08751649658073");
//        return DingTalkApprovalProcess::getContractApprovalProcessInfo();
////        return DingTalkDeptUserFacade::getUserInfoByUserId(110469380821615386);
         return DingTalkApprovalProcess::sendContractApprovalProcess([
            'code' => "PROC-872A0F49-288F-49ED-9199-876969152932",
            'originatorUserId' => 110469380821615386,
            'deptId' => -1,
            'approversV2' => [
                [
                    'taskActionType' => 'NONE',
                    'userIds' => "184323434437718643"
                ],
                [
                    'taskActionType' => 'NONE',
                    'userIds' => "184323434437718643"
                ],
            ],
            'formComponent' => [
                [
                    'name' => '合同标题',
                    'value' => '123'
                ],
                [
                    'name' => '合同类型',
                    'value' => 'gg'
                ],
                [
                    'name'=>'合同金额',
                    'value' => 100000
                ],
                [
                    'name' => '合同相对方',
                    'value' => 'test'
                ]
            ]
        ]);
        die();

    }

    /**
     *新增公司
     * @param AddCompanyPost $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addCompany(AddCompanyPost $request): \Illuminate\Http\JsonResponse
    {
        $this->_companyService->addCompanyService($request);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '新建公司成功',
            ResponseStatusConsts::CREATED_201_RESPONSE_STATUS
        );
    }

    /**
     * 编辑公司
     * @param int $companyId
     * @return \Illuminate\Http\JsonResponse
     */
    public function editCompany(int $companyId): \Illuminate\Http\JsonResponse
    {
        $editData = \request()->post();
        $editData['company_id'] = $companyId;
        $this->_companyService->editCompanyService($editData);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '编辑公司成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    /**
     * 删除公司
     * @param int $companyId
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteCompany(int $companyId): \Illuminate\Http\JsonResponse
    {
        $this->_companyService->patchEditCompanyService($companyId);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '删除公司成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    /**
     * 批量删除公司
     * @return \Illuminate\Http\JsonResponse
     */
    public function bulkDeleteCompany(): \Illuminate\Http\JsonResponse
    {
        $companyIds = \request()->post('company_ids');
        $this->_companyService->bulkDeleteCompany($companyIds);
        return ResponseFunc::returnJson(
            'ok',
            null,
            '批量删除公司成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    /**
     * 获取公司下拉
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCompanySelect(): \Illuminate\Http\JsonResponse
    {
        return ResponseFunc::returnJson(
            'ok',
            $this->_companyService->getCompanySelect(),
            '获取公司下拉成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    /**
     * 获取公司列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCompanyList(ListCompanyGet $request): \Illuminate\Http\JsonResponse
    {
        $pFilters = $request->get('filters');
        $pageSize = $request->get('page_size');

        $companyList = $this->_companyService->getCompanyList($pageSize,$pFilters);
        return ResponseFunc::returnJson(
            'ok',
            $companyList,
            '获取公司列表成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    /**
     * 获取公司详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCompanyInfo($companyId): \Illuminate\Http\JsonResponse
    {
        return ResponseFunc::returnJson(
            'ok',
            $this->_companyService->getCompanyInfoService($companyId),
            '获取公司详情成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }



}